class GYKeyboard
{
	private static _instance:GYKeyboard;
	public static getInstance():GYKeyboard
	{
		return GYKeyboard._instance = GYKeyboard._instance || new GYKeyboard;
	}		
	private _keyListeners:IKeyBoardObject[];
	private _keyDownDict:any;
	/**输入焦点中，设置为true则无法触发键盘响应*/public inputFocus:boolean;
	public constructor()
	{var s = this;
		s._keyDownDict = {};
		s._keyListeners = new Array<IKeyBoardObject>();
		// GYSprite.stage.addEventListener(KeyboardEvent.KEY_DOWN, s.kDown, GYSprite.stage);
		document.addEventListener("keydown", function(e):void{s.kDown(e)});
		// GYSprite.stage.addEventListener(KeyboardEvent.KEY_UP, s.kUp, GYSprite.stage);
		document.addEventListener("keyup", function(e):void{s.kUp(e)});
	}
	public addKeyListener(k:IKeyBoardObject):void
	{var s = this;
		var tK:IKeyBoardObject;
		var ind:number=s._keyListeners.indexOf(k);
		if(ind > -1)
			s._keyListeners.splice(ind,1);
		s._keyListeners.push(k);				
		
	}
	public removeKeyListener(k:IKeyBoardObject):void
	{var s = this;
		var ind:number=s._keyListeners.indexOf(k);
		if(ind == -1)return;
		s._keyListeners.splice(ind,1);
	}
	private kDown(e:KeyboardEvent):void
	{var s = this;			
		var keyCode:number = e.keyCode;
		s._keyDownDict[keyCode]=CommonUtil.loopTime;
		if(s._keyListeners.length == 0)return;
		if(s.inputFocus)return;
		var len:number;
		var k:IKeyBoardObject;
		len = s._keyListeners.length;
		while(--len>-1)
		{
			k = s._keyListeners[len];
			if(k.disposed)
			{
				s._keyListeners.splice(len, 1);
				continue;
			}
			k.kDown(keyCode,e);
			if(k.keyFocus())break;
		}
	}
	private kUp(e:KeyboardEvent):void
	{var s = this;			
		var keyCode:number = e.keyCode;
		s._keyDownDict[keyCode]= 0;
		if(s._keyListeners.length == 0)return;
		if(s.inputFocus)return;
		var len:number;
		var k:IKeyBoardObject;
		len = s._keyListeners.length;
		while(--len>-1)
		{
			k = s._keyListeners[len];
			if(k.disposed)
			{
				s._keyListeners.splice(len, 1);
				continue;
			}
			k.kUp(keyCode,e);
			if(k.keyFocus())break;
		}
	}
	/**按下键的时间戳，0为未按下*/
	public isKeyDown(keyCode:number):number
	{var s = this;
		return s._keyDownDict[keyCode];
	}
	public releaseKey(keyCode:number):void
	{var s = this;
		if(keyCode == -1)
		{
			s._keyDownDict = {};
			return;
		}
		s._keyDownDict[keyCode]= 0;
	}
	
	public isCtrlDown():boolean
	{var s = this;
		return s._keyDownDict[Laya.Keyboard.CONTROL] > 0;	
	}
	public isAltDown():boolean
	{var s = this;
		return s._keyDownDict[Laya.Keyboard.ALTERNATE] > 0;
	}
	public isShiftDown():boolean
	{var s = this;
		return s._keyDownDict[Laya.Keyboard.SHIFT] > 0;
	}

}